package com.lzq.shiro.config;

import java.util.LinkedHashMap;
import java.util.Map;

import org.apache.log4j.Logger;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.session.mgt.SessionManager;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.CookieRememberMeManager;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.servlet.SimpleCookie;
import org.crazycake.shiro.RedisManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerExceptionResolver;

/**
 * Created by Administrator on 2017/12/11.
 */
@SuppressWarnings(value={"rawtypes"})
@Configuration
public class ShiroConfig {

    @Bean
    public ShiroFilterFactoryBean shirFilter(SecurityManager securityManager) {
//        System.out.println("ShiroConfiguration.shirFilter()");
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(securityManager);

        Map<String, String> filterChainDefinitionMap = new LinkedHashMap<String, String>();
      //注意过滤器配置顺序 不能颠倒
        //配置退出 过滤器,其中的具体的退出代码Shiro已经替我们实现了，登出后跳转配置的loginUrl
        shiroFilterFactoryBean.setLoginUrl("/login");
        // filterChainDefinitionMap.put("/logout", "logout");
        // 配置不会被拦截的链接 顺序判断
        filterChainDefinitionMap.put("/druid/**", "anon");
        // filterChainDefinitionMap.put("/static/**", "anon"); // 为什么这样写突然没用了
        filterChainDefinitionMap.put("/css/**", "anon");//css
        filterChainDefinitionMap.put("/js/**", "anon");//js
        filterChainDefinitionMap.put("/login", "anon");
        filterChainDefinitionMap.put("/register", "anon");
        filterChainDefinitionMap.put("/ajaxLogin", "anon");
        filterChainDefinitionMap.put("/ajaxRegister", "anon");
        filterChainDefinitionMap.put("/redis/**", "anon");
        filterChainDefinitionMap.put("/index", "authc,roles[admin],perms[add,remove,update,query,grank]");// 记住我 //,roles[admin],perms[add,remove,update,query]
        shiroFilterFactoryBean.setUnauthorizedUrl("/403");
        filterChainDefinitionMap.put("/**", "anon");
        //配置shiro默认登录界面地址，前后端分离中登录界面跳转应由前端路由控制，后台仅返回json数据
        // 登录成功后要跳转的链接
        shiroFilterFactoryBean.setSuccessUrl("/index");
        //未授权界面;
        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
        return shiroFilterFactoryBean;
    }
    
    
    @Bean
    public SecurityManager securityManager(@Qualifier("redisTemplate") RedisTemplate redisTemplate , @Qualifier("stringRedisTemplate")StringRedisTemplate stringRedisTemplate) {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(myShiroRealm(redisTemplate));
        // 自定义session管理 使用redis
        securityManager.setSessionManager(sessionManager(redisTemplate));
        
        return securityManager;
    }
    

    /**
     * 凭证匹配器
     * （由于我们的密码校验交给Shiro的SimpleAuthenticationInfo进行处理了
     * ）
     *
     * @return
     */
    @Bean
    public HashedCredentialsMatcher hashedCredentialsMatcher() {
        HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
        hashedCredentialsMatcher.setHashAlgorithmName("MD5");//散列算法:这里使用MD5算法;
        hashedCredentialsMatcher.setHashIterations(1);//散列的次数，比如散列两次，相当于 md5(md5(""));
        return hashedCredentialsMatcher;
    }
    
    @Bean
    public MyShiroRealm myShiroRealm(RedisTemplate redisTemplate) {
        MyShiroRealm myShiroRealm = new MyShiroRealm();
        myShiroRealm.setCredentialsMatcher(hashedCredentialsMatcher());
        myShiroRealm.setCacheManager(shiroRedisCacheManager(redisTemplate));
        myShiroRealm.setCachingEnabled(true);
        myShiroRealm.setAuthenticationCachingEnabled(false);
        myShiroRealm.setAuthorizationCachingEnabled(true);
        return myShiroRealm;
    }


    
    @Bean 
    public SimpleCookie simpleCookie() {
    	// 设置cookie名字
    	SimpleCookie cookie = new SimpleCookie(Constant.SHIRO_COOKIE_NAME);
    	
    	// 设置cookie的有效时间30天
    	
    	cookie.setMaxAge(259200);
    	return cookie;
    }
    
    /**
     * @return
     * @desc cookie管理对象
     */
    @Bean
    public CookieRememberMeManager rememberMeManager() {
    	CookieRememberMeManager cookieRememberMeManager = new CookieRememberMeManager();
    	cookieRememberMeManager.setCookie(simpleCookie());
    	return cookieRememberMeManager;
    }
    
    
    
    

    //自定义sessionManager
    @Bean
    public SessionManager sessionManager(RedisTemplate redisTemplate) {
        MySessionManager mySessionManager = new MySessionManager();
        // 设置session永不过期
        mySessionManager.setGlobalSessionTimeout(-1);
        
        
        
        MyRedisSessionDao sessionDao = new MyRedisSessionDao(redisTemplate);
        
        // 设置redis操作dao
        mySessionManager.setSessionDAO(sessionDao);
        
        // 自定义redis缓存存储器
        // mySessionManager.setCacheManager(shiroRedisCacheManager(redisTemplate));
       
        mySessionManager.setSessionValidationSchedulerEnabled(true);
        mySessionManager.setSessionValidationInterval(5 * 60 * 1000);
        mySessionManager.setSessionIdUrlRewritingEnabled(false);
        
        mySessionManager.setSessionIdCookieEnabled(true);
        
        
        
        
        mySessionManager.setSessionIdCookie(simpleCookie());
        
        
        
        return mySessionManager;
    }

    /**
     * 配置shiro redisManager
     * <p>
     * 使用的是shiro-redis开源插件
     *
     * @return
     */
    @ConfigurationProperties(prefix = "redis.shiro")
    public RedisManager redisManager() {
        return new RedisManager();
    }

    /**
     * cacheManager 缓存 redis实现
     * <p>
     * 使用的是shiro-redis开源插件
     *
     * @return
     */
    /*@Bean
    public RedisCacheManager cacheManager() {
        RedisCacheManager redisCacheManager = new RedisCacheManager();
        redisCacheManager.setRedisManager(redisManager());
        redisCacheManager.setKeyPrefix("shiro_redis:");
        return redisCacheManager;
    }*/
    
    @Bean
    public ShiroRedisCacheManager shiroRedisCacheManager(RedisTemplate redisTemplate) {
    	String keyPrefix = "shiro_session:";
    	ShiroRedisCacheManager cacheManager = new ShiroRedisCacheManager(redisTemplate);
    	cacheManager.createCache(keyPrefix);
    	return cacheManager;
    }

    /**
     * RedisSessionDAO shiro sessionDao层的实现 通过redis
     * <p>
     * 使用的是shiro-redis开源插件
     */
   /* @Bean
    public MyRedisSessionDao redisSessionDAO(RedisTemplate redisTemplate) {
    	
    	MyRedisSessionDao sessionDao = new MyRedisSessionDao(redisTemplate);
    	
    	return sessionDao;
    	
        RedisSessionDAO redisSessionDAO = new RedisSessionDAO();
        redisSessionDAO.setRedisManager(redisManager());
//      Custom your redis key prefix for session management, if you doesn't define this parameter,
//      shiro-redis will use 'shiro_redis_session:' as default prefix
//      redisSessionDAO.setKeyPrefix("");
        return redisSessionDAO;
    }
*/
    /**
     * 开启shiro aop注解支持.
     * 使用代理方式;所以需要开启代码支持;
     *
     * @param securityManager
     * @return
     */
    @Bean
    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager) {
        AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
        authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
        return authorizationAttributeSourceAdvisor;
    }

    
}
